package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.venueservice.dao.ServiceItemDiscountMapper;
import com.eastfair.venueservice.dto.ServiceItemDiscountDTO;
import com.eastfair.venueservice.entity.ServiceItem;
import com.eastfair.venueservice.entity.ServiceItemDiscount;
import com.eastfair.venueservice.exceptioncode.VenueServiceExceptionCode;
import com.eastfair.venueservice.service.ServiceItemDiscountService;
import com.eastfair.venueservice.vo.ServiceItemDiscountVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* <p>
    * 业务实现类
    * 服务折扣利率
    * </p>
*
* @author linan
* @date 2022-07-28
*/
@Slf4j
@Service
//@DS("#thread.tenant")
public class ServiceItemDiscountServiceImpl extends SuperServiceImpl<ServiceItemDiscountMapper, ServiceItemDiscount> implements ServiceItemDiscountService {


    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<ServiceItemDiscount> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
// TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }



    @Override
    protected R<Boolean> handlerSave(ServiceItemDiscount model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<ServiceItemDiscount> list(ServiceItemDiscountDTO modelDTO, List<Long> ids) {
        return ((ServiceItemDiscountService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'serviceItemId', #args[0]?.serviceItemId}," +
                            "{'spaceId', #args[0]?.spaceId}," +
                            "{'startDate', #args[0]?.startDate}," +
                            "{'endDate', #args[0]?.endDate}," +
                            "{'discount', #args[0]?.discount}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<ServiceItemDiscount> listOfCache(ServiceItemDiscountDTO modelDTO, List<Long> ids) {
        //查询
        QueryWrapper<ServiceItemDiscount> queryWrapper = new QueryWrapper<>();
        if (modelDTO != null) {
            queryWrapper.lambda().eq(modelDTO.getServiceItemId() != null, ServiceItemDiscount::getServiceItemId, modelDTO.getServiceItemId());
            queryWrapper.lambda().eq(modelDTO.getSpaceId() != null, ServiceItemDiscount::getSpaceId, modelDTO.getSpaceId());
            queryWrapper.lambda().eq(modelDTO.getStartDate() != null, ServiceItemDiscount::getStartDate, modelDTO.getStartDate());
            queryWrapper.lambda().eq(modelDTO.getEndDate() != null, ServiceItemDiscount::getEndDate, modelDTO.getEndDate());
            queryWrapper.lambda().eq(modelDTO.getDiscount() != null, ServiceItemDiscount::getDiscount, modelDTO.getDiscount());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(ServiceItemDiscount::getId, ids);
        }
        queryWrapper.lambda().eq(ServiceItemDiscount::getIsDeleted, BusinessConstant.DELETE_NO);
        List<ServiceItemDiscount> modelList = list(queryWrapper);
        return modelList;
    }

    @Override
    public void saveDiscount(ServiceItem serviceItem, List<ServiceItemDiscountDTO> serviceItemDiscountList) {
        // 删除历史折扣配置
        update(new UpdateWrapper<ServiceItemDiscount>().lambda().eq(ServiceItemDiscount::getServiceItemId,serviceItem.getId())
                .eq(ServiceItemDiscount::getIsDeleted,BusinessConstant.NO)
                .set(ServiceItemDiscount::getIsDeleted,BusinessConstant.YES));
        if (CollectionUtils.isNotEmpty(serviceItemDiscountList)) {
            // 校验日期
            checkDate(serviceItemDiscountList);
            for (ServiceItemDiscountDTO serviceItemDiscountDTO : serviceItemDiscountList) {
                ServiceItemDiscount serviceItemDiscount = BeanUtil.copyProperties(serviceItemDiscountDTO, ServiceItemDiscount.class, "id");
                serviceItemDiscount.setServiceItemId(serviceItem.getId());
                save(serviceItemDiscount);
            }
        }
    }

    /**
     * 校验日期
     * @param serviceItemDiscountList  serviceItemDiscountList
     */
    private void checkDate(List<ServiceItemDiscountDTO> serviceItemDiscountList) {
        for (int i = 0; i < serviceItemDiscountList.size(); i++) {
            ServiceItemDiscountDTO serviceItemDiscountI = serviceItemDiscountList.get(i);
            if(serviceItemDiscountI.getStartDate().isAfter(serviceItemDiscountI.getEndDate())){
                // 服务折扣开始日期不可以大于折扣日期
                throw BizException.wrap(VenueServiceExceptionCode.SERVICE_DISCOUNT_DATE_ERROR);
            }
            for (int j = 0; j < serviceItemDiscountList.size(); j++) {
                if (i != j) {
                    ServiceItemDiscountDTO serviceItemDiscountJ = serviceItemDiscountList.get(j);
                    Boolean interSection = isInterSection(serviceItemDiscountI.getStartDate(), serviceItemDiscountI.getEndDate(), serviceItemDiscountJ.getStartDate(), serviceItemDiscountJ.getEndDate());
                    if(interSection){
                        // 服务折扣时间不可以有交集
                        throw BizException.wrap(VenueServiceExceptionCode.SERVICE_DISCOUNT_INTERSECTION_EXISTS);
                    }
                }
            }
        }
    }

    /***
     *
     * @param startDateOne 第一个时间段的开始时间
     * @param endDateOne 第一个时间段的结束时间
     * @param startDateTwo 第二个时间段的开始时间
     * @param endDateTwo 第二个时间段的结束时间
     * @return Boolean
     */
    public static Boolean isInterSection(LocalDate startDateOne, LocalDate endDateOne, LocalDate startDateTwo, LocalDate endDateTwo) {
        LocalDate maxStartDate = startDateOne;
        if (maxStartDate.isBefore(startDateTwo)) {
            maxStartDate = startDateTwo;
        }
        LocalDate minEndDate = endDateOne;
        if (endDateTwo.isBefore(minEndDate)) {
            minEndDate = endDateTwo;
        }
        return maxStartDate.isBefore(minEndDate) || (maxStartDate.compareTo(minEndDate) == 0);
    }

    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public ServiceItemDiscountVO doToVo(ServiceItemDiscount model) {
        ServiceItemDiscountVO modelVo = new ServiceItemDiscountVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<ServiceItemDiscountVO> doToVos(List<ServiceItemDiscount> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<ServiceItemDiscountVO> result = new ArrayList<>();
        for (ServiceItemDiscount model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }
}
